package com.gdufe.studytogether.service.application.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gdufe.studytogether.domain.R;
import com.gdufe.studytogether.domain.pojo.*;
import com.gdufe.studytogether.mapper.ApplicationMapper;
import com.gdufe.studytogether.mapper.GroupMapper;
import com.gdufe.studytogether.service.application.ApplicationService;
import com.gdufe.studytogether.service.competition.CompetitionService;
import com.gdufe.studytogether.service.group.GroupService;
import com.gdufe.studytogether.service.user.UserService;
import com.gdufe.studytogether.service.usergroup.UserGroupService;
import com.gdufe.studytogether.utils.UserThreadLocal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.util.List;

@Service
public class ApplicationServiceImpl extends ServiceImpl<ApplicationMapper,Application> implements ApplicationService {

    @Autowired
    ApplicationMapper applicationMapper;
    @Autowired
    @Lazy
    GroupService groupService;
    @Autowired
    UserGroupService userGroupService;
    @Autowired
    CompetitionService competitionService;
    @Autowired
    GroupMapper groupMapper;
    @Autowired
    UserService userService;

    @Override
    public R getApplication() throws Exception {
        Integer uId = UserThreadLocal.get();
        QueryWrapper<Application> qw=new QueryWrapper<>();
        qw.eq("targetId",uId);
        List<Application> applications = applicationMapper.selectList(qw);
        for (int i = 0; i < applications.size(); i++) {
            Application application=applications.get(i);
            User user = userService.getById(application.getUid());
            application.setUsername(user.getUsername());
            Group group = groupService.getById(application.getGid());
            if (group==null||!"0".equals(group.getStatus())){
                //队伍已解散
                deleteApplication(application.getId());
                continue;
            }
            application.setGroupName(group.getGroupName());
            Competition competition = competitionService.getById(group.getCid());
            if(competition==null||!"0".equals(competition.getStatus())){
                deleteApplication(application.getId());
                continue;//比赛已删除
            }
            application.setCompetitionName(competition.getName());
        }

        return R.ok(applications);
    }


    public R addApplication(Application application) throws Exception {
        Integer uid = UserThreadLocal.get();
        Group group = groupService.getById(application.getGid());
        if(group.getLeaderid()==uid&&"0".equals(group.getStatus())){
            return R.error("请勿申请加入自己的队伍");
        }
        if (group==null||"1".equals(group.getStatus())){
            return R.error("队伍不存在");
        }
        Integer cid = group.getCid();
        Competition competition = competitionService.getById(cid);
        if (competition==null||"1".equals(competition.getStatus())){
            return R.error("比赛不存在");
        }
        LocalDate now = LocalDate.now();
        if (now.isAfter(competition.getEndTime())){
            return R.error("比赛已结束");
        }
        Integer currentSize = group.getCurrentSize();
        Integer memberSize = group.getMemberSize();
        if (currentSize>=memberSize){
            return R.error("队伍已满");
        }
        List<Integer> list = groupMapper.getGroupIdByUIdAndCid(uid, group.getCid());
        if (list.size()>=1){
            for (Integer gid : list) {
                QueryWrapper<Group> qw = new QueryWrapper<>();
                qw.eq("id",gid);
                qw.eq("status","0");
                List<Group> groups = groupMapper.selectList(qw);
                if (groups.size()>0){
                    return R.error("您已加入比赛队伍,请勿重复申请");
                }
            }

        }

        QueryWrapper<Application> applicationQueryWrapper = new QueryWrapper<>();
        applicationQueryWrapper.eq("uid",uid);
        applicationQueryWrapper.eq("gid",application.getGid());
        applicationQueryWrapper.eq("type","0");
        List<Application> applications = applicationMapper.selectList(applicationQueryWrapper);
        if (applications!=null&&applications.size()>0){
            return R.error("您已申请，请勿重复申请");
        }
        application.setUid(uid);
        application.setType("0");
        application.setTargetId(group.getLeaderid());
        applicationMapper.insert(application);
        return R.ok("申请成功");
    }

    @Override
    public R deleteApplication(Integer id) throws Exception {
        Integer uid = UserThreadLocal.get();
        Application application = applicationMapper.selectById(id);
        if (application==null){
            return R.error("通知不存在");
        }
        if (application.getTargetId()!=uid){
            return R.error("删除失败");
        }
        applicationMapper.deleteById(id);
        return R.ok();
    }

    @Override
    public void deleteApplicationByGid(Integer id) {
        QueryWrapper<Application> applicationQueryWrapper = new QueryWrapper<>();
        applicationQueryWrapper.eq("gid",id);
        applicationMapper.delete(applicationQueryWrapper);
    }

    @Override
    @Transactional
    public R agreeApplication(Integer id) throws Exception {
        Application application = applicationMapper.selectById(id);
        Integer uid = UserThreadLocal.get();
        Integer gid = application.getGid();
        Group group = groupService.getById(gid);
        if(group==null||!"0".equals(group.getStatus())){
            applicationMapper.deleteById(id);
            return R.error("队伍不存在");
        }
        if(uid!=group.getLeaderid()){
            return R.error("只有队长才能同意申请！");
        }


        groupService.joinGroup(application);
        application.setType("1");
        application.setTargetId(application.getUid());
        applicationMapper.updateById(application);


        return R.ok();
    }

    @Override
    public R disagreeApplication(Integer id) throws Exception {
        Application application = applicationMapper.selectById(id);
        Integer uid = UserThreadLocal.get();
        Integer gid = application.getGid();
        Group group = groupService.getById(gid);
        if(group==null||!"0".equals(group.getStatus())){
            applicationMapper.deleteById(id);
            return R.error("队伍不存在");
        }
        if(uid!=group.getLeaderid()){
            return R.error("只有队长才能同意申请！");
        }

        application.setType("2");
        application.setTargetId(application.getUid());
        applicationMapper.updateById(application);
        return R.ok();
    }
}
